package com.suray.basic.wcs.utils.thread;

import com.suray.basic.wcs.utils.LoggerType;
import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.basic.wcs.utils.ModuleType;
import com.suray.basic.wcs.utils.WcsFuncUtil;

/**
 * 循环线程
 */
public abstract class BaseThread extends Thread{

    /**
     * 线程循环调用时间
     */
    private long cycleTime;
    /**
     * 控制线程运行
     */
    private boolean running;

    private ModuleType module;

    private Class<?> clazz;

    private void setCycleTime(long cycleTime) {
        this.cycleTime = cycleTime;
    }

    public BaseThread(String name, long cycleTime, ModuleType module) {
        super(name);
        this.cycleTime = cycleTime;
        running = true;
        this.clazz = this.getClass();
        this.module = module;
    }

    public BaseThread(String name, long cycleTime) {
        super(name);
        this.cycleTime = cycleTime;
        running = true;
        this.clazz = this.getClass();
        this.module = ModuleType.DEFAULT;
    }

    public BaseThread(String name, long cycleTime, Class<?> clazz) {
        super(name);
        this.cycleTime = cycleTime;
        running = true;
        this.clazz = clazz;
        this.module = ModuleType.DEFAULT;
    }

    @Override
    public void run() {
        try {
            init();
        } catch (Exception e) {
            LoggerUtil.warn("初始化失败！", clazz);
            WcsFuncUtil.exceptionLog(e, this.getClass());
        }

        if (cycleTime > 0) {
            while (running) {
                try {
                    process();
                } catch (Exception e) {
                    WcsFuncUtil.exceptionLog(module, LoggerType.ERROR, null, null, e, this.getClass());
                }

                if (cycleTime > 0) {
                    WcsFuncUtil.delay(cycleTime);
                }
            }
        } else {
            while (running) {
                try {
                    process();
                } catch (Exception e) {
                    WcsFuncUtil.exceptionLog(module, LoggerType.ERROR, null, null, e, this.getClass());
                }
            }
        }
    }

    /**
     * 修改线程循环时间
     * @param cycleTime
     */
    public void changeCycleTime(long cycleTime) {
        this.cycleTime = cycleTime;
    }

    /**
     * 初始化数据
     */
    protected void init() {

    }

    /**
     * 终止线程循环
     */
    public void endThread() {
        running = false;
    }

    /**
     * 线程运行主体
     */
    protected abstract void process();
}
